﻿var ns = namespace("kaskelot.sp.ui");

ns.byggnadkontaktperson = function () {

	function init() {
		$("#kontaktperson-search-button").click(
			function () {
				searchKontaktpersoner();
			}
		);

		$("#kontaktperson-form #kontaktperson-search-input-container").keypress(
			function (event) {
				if (event.which === 13) {
					searchKontaktpersoner();
					event.stopPropagation();
				}
			}
		);
	}

	function getKontaktpersoner(options) {
		var id = getParameterByName('ByggnadId');

		var defaults = {
			selector: "kontaktperson-results",
			template: "kontaktperson-template"
		};
		var settings = $.extend({}, defaults, options);

		$(".blockable-container").block({ message: null });

		$.ajax({
			url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientByggnadService.svc/GetKontaktpersonListByByggnad",
			type: "GET",
			data: { id: id },
			processData: true,
			cache: false,
			success:
				function (data) {
					if (!data.GetKontaktpersonListByByggnadResult.HasError) {
						$("#" + settings.selector + " tbody").html(
							$("#" + settings.template).render(data.GetKontaktpersonListByByggnadResult.Data)
						);
					}
					$(".blockable-container").unblock();
				},
			error:
				function (xhr) {
					$(".blockable-container").unblock();
					kaskelot.sp.ui.prompts.showErrorPrompt(xhr.responseText);
				}
		});
	}

	function showNewKontaktpersonForm() {
		var id = "";
		var selector = "#person-form";
		kaskelot.sp.ui.formutils.getAndShowForm({
			params: {
				formName: "PersonForm",
				idString: id
			},
			selector: selector,
			openFunction: function () {
				$.ajax({
					url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientPersonService.svc/GetKontaktpersonTypId",
					type: "GET",
					data: { },
					processData: true,
					cache: false,
					success:
						function (data) {
							if (!data.GetKontaktpersonTypIdResult.HasError) {
								$("#person-form #Typer").html('<option value="' + data.GetKontaktpersonTypIdResult.Data + '">Kontaktperson</option>');
								$("#Typer").closest(".form-row").hide();
							}
						},
					error:
						function (xhr) {
							kaskelot.sp.ui.prompts.showErrorPrompt(xhr.responseText);
						}
				});
			},
			okFunction: function () {
				$(selector).parent().block({ message: null });

				var prog = kaskelot.sp.ui.formutils.getObject(selector);
				var data = "{\"form\":" + JSON.stringify(prog) + "}";
				var method = "CreatePerson";

				$.ajax({
					url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientPersonService.svc/" + method,
					data: data,
					type: "POST",
					processData: false,
					contentType: "application/json",
					dataType: "json",
					success: function (resp) {
						if (resp[method + "Result"].HasError) {
							kaskelot.sp.ui.formutils.showError(selector, resp[method + "Result"].ErrorMessage);
						}
						else {
							var byggnadId = getParameterByName('ByggnadId');
							var personId = resp[method + "Result"].Data;

							$.ajax({
								url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientPersonService.svc/AddNewKontaktpersonToByggnad",
								type: "GET",
								data: { ByggnadId: byggnadId, PersonId: personId },
								processData: true,
								cache: false,
								success:
									function (data) {
										if (!data.AddNewKontaktpersonToByggnadResult.HasError) {
											$(selector).parent().unblock();
											$(selector).dialog("close");
											getKontaktpersoner();
										}
									},
								error:
									function (xhr) {
										kaskelot.sp.ui.prompts.showErrorPrompt(xhr.responseText);
										$(selector).parent().unblock();
									}
							});
						}
					},
					error: function (xhr) {
						kaskelot.sp.ui.formutils.showError(selector, xhr.responseText);
					}
				});
			}
		});
	}

	function showDeleteForm(id) {
		var byggnadid = getParameterByName('ByggnadId');
		var selector = "#remove-kontaktperson-form";
		kaskelot.sp.ui.formutils.getAndShowForm({
			params: {
				formName: "RemoveKontaktpersonForm",
				idString: id,
				parentIdString: byggnadid
			},
			selector: selector,
			openFunction: function () {
				$("#remove-kontaktperson-form #Namn").attr("disabled", "disabled");
				$("#remove-kontaktperson-form #Personnummer").attr("disabled", "disabled");
			},
			okFunction: function () {
				var prog = kaskelot.sp.ui.formutils.getObject(selector);
				var data = "{\"form\":" + JSON.stringify(prog) + "}";

				var method = "RemoveKontaktpersonFromByggnad";

				$.ajax({
					url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientPersonService.svc/" + method,
					data: data,
					type: "POST",
					processData: false,
					contentType: "application/json",
					dataType: "json",
					success: function (resp) {
						if (resp[method + "Result"].HasError) {
							kaskelot.sp.ui.formutils.showError(selector, resp[method + "Result"].ErrorMessage);
						}
						else {
							$(selector).dialog("close");
							getKontaktpersoner();
						}
					},
					error: function (xhr) {
						kaskelot.sp.ui.formutils.showError(selector, xhr.responseText);
					}
				});
			}
		});
	}

	function showExistingKontaktpersonForm() {
		var id = getParameterByName('ByggnadId');
		var selector = "#kontaktperson-form";
		kaskelot.sp.ui.formutils.getAndShowForm({
			params: {
				formName: "KontaktpersonForm",
				idString: "",
				parentIdString: id
			},
			selector: selector,
			openFunction: function () {
				$(".chzn-select-deselect").chosen({ disable_search: true });
			},
			okFunction: function () {
				$(selector).parent().block();

				var prog = kaskelot.sp.ui.formutils.getObject(selector);
				var data = "{\"form\":" + JSON.stringify(prog) + "}";

				var method = "AddKontaktpersonToByggnad";

				$.ajax({
					url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientPersonService.svc/" + method,
					data: data,
					type: "POST",
					processData: false,
					contentType: "application/json",
					dataType: "json",
					success: function (resp) {
						if (resp[method + "Result"].HasError) {
							kaskelot.sp.ui.formutils.showError(selector, resp[method + "Result"].ErrorMessage);
						}
						else {
							$(selector).dialog("close");
							getKontaktpersoner();
						}
					},
					error: function (xhr) {
						kaskelot.sp.ui.formutils.showError(selector, xhr.responseText);
					}
				});
			}
		});
	}

	function searchKontaktpersoner() {
		// Parametrar
		var typ = $("#Typ").val();
		var inaktiva = $("#InaktivaCheckbox").prop('checked');
		var personnummer = $("#PersonnummerTextbox").val();
		var namn = $("#NamnTextbox").val();

		$("#kontaktperson-form").block({ message: '<h1>Var god vänta...</h1>' });

		$.ajax({
			url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientPersonService.svc/SearchPersoner",
			type: "GET",
			data: { fritext: null, visaInaktiva: inaktiva, typId: typ, postnummer: null, personnummer: personnummer, namn: namn },
			processData: true,
			cache: false,
			success:
				function (data) {
					if (!data.SearchPersonerResult.HasError) {
						$("#kontaktperson-search-results tbody").html(
							$("#search-kontaktperson-template").render(data.SearchPersonerResult.Data)
						);
					}
					$("#kontaktperson-form").unblock();
				},
			error:
				function (xhr) {
					$("#kontaktperson-form").unblock();
					kaskelot.sp.ui.prompts.showErrorPrompt(xhr.responseText);
				}
		});
	}

	function selectKontaktperson(id) {
		$(".selected-row").removeClass("selected-row");
		$("#" + id).addClass("selected-row");
		$("#kontaktperson-form #PersonId").val(id);
	}

	function selectKontaktpersonToRemove(name, id) {
		$("#remove-kontaktperson-form #PersonId").val(id);
	}

	return {
		getKontaktpersoner: getKontaktpersoner,
		showExistingKontaktpersonForm: showExistingKontaktpersonForm,
		showNewKontaktpersonForm: showNewKontaktpersonForm,
		showDeleteForm: showDeleteForm,
		searchKontaktpersoner: searchKontaktpersoner,
		selectKontaktperson: selectKontaktperson,
		selectKontaktpersonToRemove: selectKontaktpersonToRemove,
		init: init
	};
}();